<template>
  <div>
    <el-dialog
      class="custom-dialog"
      v-model="dialogVisible"
      :title="title"
      width="500px"
      @close="handleClose"
    >
      <el-form
        class="data-form"
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="字典名称" prop="name">
          <el-input
            class="data-input"
            v-model="form.name"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
        <el-form-item label="字典编码" prop="code">
          <el-input class="data-input" v-model="form.code" placeholder="请输入">
          </el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="(item, index) of dictOptions['status']"
              :key="index"
              :value="Number(item.value)"
              >{{ item.name }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            class="data-input"
            v-model="form.remark"
            type="textarea"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
        <div class="title">
          属性配置
          <el-button type="primary" link @click="handleAdd"
            ><el-icon><CirclePlusFilled /></el-icon
          ></el-button>
        </div>
        <table>
          <thead>
            <tr>
              <th style="width: 200px">属性名称</th>
              <th style="width: 150px">属性键值</th>
              <th style="width: 150px">回显样式</th>
              <th style="width: 60px">状态</th>
              <th style="width: 50px">操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(item, index) of form.dictionaryValueInfos" :key="index">
              <td style="width: 200px">
                <el-form-item
                  class="table-form-item"
                  label=""
                  :prop="'dictionaryValueInfos.' + index + '.name'"
                  :rules="rules.dictionaryName"
                >
                  <el-input
                    class="data-input"
                    v-model="item.name"
                    placeholder="请输入"
                  ></el-input>
                </el-form-item>
              </td>
              <td style="width: 150px">
                <el-form-item
                  class="table-form-item"
                  label=""
                  :prop="'dictionaryValueInfos.' + index + '.value'"
                  :rules="rules.dictionaryValue"
                >
                  <el-input
                    class="data-input"
                    v-model="item.value"
                    placeholder="请输入"
                  >
                  </el-input>
                </el-form-item>
              </td>
              <td style="width: 150px">
                <el-form-item
                  class="table-form-item"
                  label=""
                  :prop="'dictionaryValueInfos.' + index + '.styleName'"
                >
                  <el-select
                    class="data-input"
                    v-model="item.styleName"
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="(item, index) of styleNameOptions"
                      :key="index"
                      :label="item.name"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </td>
              <td style="width: 60px">
                <el-form-item
                  class="table-form-item"
                  label=""
                  :prop="'dictionaryValueInfos.' + index + '.status'"
                >
                  <el-switch
                    :active-value="1"
                    :inactive-value="0"
                    v-model="item.status"
                  />
                </el-form-item>
              </td>
              <td style="width: 50px">
                <el-form-item class="table-form-item" label="">
                  <el-button type="danger" link @click="handleRemove(index)"
                    ><el-icon><RemoveFilled /></el-icon
                  ></el-button>
                </el-form-item>
              </td>
            </tr>
          </tbody>
        </table>
      </el-form>
      <template #footer>
        <el-button @click="handleClose(false)">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useDict } from '@/hooks/useDict'
const { dictOptions, initListDictOptions } = useDict()
import { CirclePlusFilled, RemoveFilled } from '@element-plus/icons-vue'
import {
  getDictDetail,
  dictAdd,
  dictEdit,
} from '@/api/manager/systemManage/dict.js'
defineOptions({
  name: 'AddDialog',
})
const props = defineProps({
  detail: {
    type: Object,
  },
})
watch(
  () => props.detail,
  () => {
    if (props.detail.pkid) {
      handleDetail(props.detail.pkid)
    }
  },
)
const emit = defineEmits(['close'])
const title = ref('')
const dialogVisible = ref(false)
const handleClose = (isFlash = false) => {
  form.value = { status: 1, dictionaryValueInfos: [] }
  dialogVisible.value = false
  formRef.value.clearValidate()
  emit('close', isFlash)
}
const styleNameOptions = ref([
  {
    name: '默认(default)',
    value: 'default',
  },
  {
    name: '主要(primary)',
    value: 'primary',
  },
  {
    name: '成功(success)',
    value: 'success',
  },
  {
    name: '信息(info)',
    value: 'info',
  },
  {
    name: '警告(warning)',
    value: 'warning',
  },
  {
    name: '危险(danger)',
    value: 'danger',
  },
])
const formRef = ref(null)
const form = ref({
  status: 1,
  dictionaryValueInfos: [],
})
const rules = ref({
  name: [{ required: true, message: '请输入字典名称', trigger: 'blur' }],
  code: [{ required: true, message: '请输入字典编码', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'blur' }],
  dictionaryName: [
    { required: true, message: '请输入属性名称', trigger: 'blur' },
  ],
  dictionaryValue: [
    // { required: true, message: '请输入属性键值', trigger: 'blur' },
    // {
    //   pattern: /^[A-Za-z0-9\-]+$/,
    //   message: '属性键值只能为大小写字母、数字、-',
    //   trigger: 'blur',
    // },
  ],
})
const handleDetail = async (pkid) => {
  const res = await getDictDetail({ pkid: pkid })
  console.log('res', res)
  // res.data.dictionaryValueInfos.forEach((item) => {
  //   item.value = item.value.replace(`${res.data.code}_`, '')
  // })
  form.value = { ...res.data }
}
const handleAdd = () => {
  form.value.dictionaryValueInfos.push({
    name: '',
    value: '',
    styleName: '',
    status: 1,
  })
}
const handleRemove = (index) => {
  form.value.dictionaryValueInfos.splice(index, 1)
}
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid, fields) => {
    if (valid) {
      const param = JSON.parse(JSON.stringify(form.value))
      // param.dictionaryValueInfos.forEach((item) => {
      //   item.value = param.code + '_' + item.value
      // })
      let res
      if (form.value.pkid) {
        res = await dictEdit(form.value.pkid, param)
      } else {
        res = await dictAdd(param)
      }
      if (res.success) {
        handleClose(true)
      } else {
        ElMessage.error(res.message)
      }
    } else {
      ElMessage.warning('请正确录入信息')
    }
  })
}
defineExpose({ dialogVisible, title })
onMounted(() => {
  initListDictOptions(['status'])
})
</script>
<style lang="scss" scoped>
.title {
  width: 100%;
  padding: 0 0 5px 15px;
  font-size: 14px;
  line-height: 14px;
  font-weight: 400;
  color: #151515;
  position: relative;
  &::before {
    content: ' ';
    position: absolute;
    width: 4px;
    height: 16px;
    background: linear-gradient(0deg, #4575ee 0%, #6297f5 100%);
    border-radius: 2px;
    top: 6px;
    left: 0px;
  }
  .el-button {
    margin-left: 10px;
  }
}
:deep(.table-form-item) {
  width: 100%;
  .el-form-item__content {
    margin-left: 0 !important;
  }
}
table {
  th {
    height: 30px;
    text-align: left;
    padding: 0 5px;
  }
  td {
    padding: 0 5px;
  }
}
</style>
